package tools

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/fatih/color"
)

func (t Command) Grep() {
	if len(os.Args) != 4 {
		fmt.Println("请求参数有误！请参考：yt grep yu /app/demo.tt ")
		return
	}
	key := os.Args[2]
	filepath := os.Args[3]

	// 打开文件
	file, err := os.Open(filepath)
	if err != nil {
		fmt.Printf("Error when opening file: %s\r\n", err)
	}
	defer file.Close()

	// 创建 Reader 对象
	reader := bufio.NewReader(file)

	// 按行读取文件
	c := color.New(color.FgRed).Add(color.Underline)

	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Printf("Error while reading file: %s\r\n", err)
		}
		if strings.Contains(line, key) {
			ls := strings.Split(line, key)
			for i := 0; i < len(ls); i++ {
				fmt.Print(ls[i])
				if i < len(ls)-1 {
					c.Printf("%s", key)
				}
			}
		}
	}
}
